<script>
import { changePassword } from '@/api/user'
import { useUserStore } from '@/store/user'
import { computed, ref } from 'vue'

export default {
  setup() {
    const userStore = useUserStore()
    const form = ref(null)
    const passwordStrength = ref(0)

    const formData = ref({
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
    })

    const strengthText = computed(() => {
      const texts = ['弱', '中', '强']
      return texts[passwordStrength.value - 1] || ''
    })

    const rules = {
      oldPassword: {
        rules: [
          { required: true, errorMessage: '请输入当前密码' },
        ],
      },
      newPassword: {
        rules: [
          { required: true, errorMessage: '请输入新密码' },
          { minLength: 6, errorMessage: '密码不能少于6位' },
        ],
      },
      confirmPassword: {
        rules: [
          { required: true, errorMessage: '请确认新密码' },
          {
            validateFunction: (rule, value, data) => {
              return value === data.newPassword
            },
            errorMessage: '两次输入的密码不一致',
          },
        ],
      },
    }

    const checkPasswordStrength = (password) => {
      let strength = 0
      if (password.length >= 6)
        strength++
      if (/[A-Z]/.test(password) && /[a-z]/.test(password))
        strength++
      if (/\d/.test(password) && /[^A-Z0-9]/i.test(password))
        strength++
      passwordStrength.value = strength
    }

    const handleSubmit = async () => {
      try {
        const valid = await form.value.validate()
        if (!valid)
          return

        await changePassword(formData.value)

        uni.showToast({
          title: '密码修改成功',
          icon: 'success',
        })

        setTimeout(() => {
          userStore.logout()
          uni.reLaunch({
            url: '/pages/login/index',
          })
        }, 1500)
      }
      catch (error) {
        console.error('修改密码失败:', error)
      }
    }

    return {
      form,
      formData,
      rules,
      passwordStrength,
      strengthText,
      checkPasswordStrength,
      handleSubmit,
    }
  },
}
</script>

<template>
  <view class="change-password-container">
    <view class="change-password-header">
      <text class="title">
        修改密码
      </text>
    </view>

    <view class="change-password-form">
      <uni-forms ref="form" :model-value="formData" :rules="rules">
        <uni-forms-item name="oldPassword">
          <uni-easyinput
            v-model="formData.oldPassword"
            type="password"
            placeholder="请输入当前密码"
          />
        </uni-forms-item>

        <uni-forms-item name="newPassword">
          <uni-easyinput
            v-model="formData.newPassword"
            type="password"
            placeholder="请输入新密码"
            @input="checkPasswordStrength"
          />
          <view class="password-strength">
            <text>密码强度：</text>
            <view class="strength-bars">
              <view
                v-for="(item, index) in 3"
                :key="index"
                class="strength-bar"
                :class="{ active: passwordStrength >= index + 1 }"
              />
            </view>
            <text class="strength-text">
              {{ strengthText }}
            </text>
          </view>
        </uni-forms-item>

        <uni-forms-item name="confirmPassword">
          <uni-easyinput
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请确认新密码"
          />
        </uni-forms-item>
      </uni-forms>

      <button class="submit-btn" type="primary" @click="handleSubmit">
        确认修改
      </button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.change-password-container {
  padding: 40rpx;

  .change-password-header {
    text-align: center;
    margin-bottom: 60rpx;

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .change-password-form {
    .password-strength {
      display: flex;
      align-items: center;
      margin-top: 10rpx;
      font-size: 24rpx;
      color: #666;

      .strength-bars {
        display: flex;
        gap: 10rpx;
        margin: 0 10rpx;

        .strength-bar {
          width: 40rpx;
          height: 10rpx;
          background-color: #ddd;
          border-radius: 5rpx;

          &.active {
            &:nth-child(1) { background-color: #ff4d4f; }
            &:nth-child(2) { background-color: #faad14; }
            &:nth-child(3) { background-color: #52c41a; }
          }
        }
      }
    }

    .submit-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      margin: 40rpx 0;
      background-color: #007AFF;
      border-radius: 44rpx;
    }
  }
}
</style>
